<template>
<view v-show="show">
	<view class="chj_imgEdit">
		<view class="history_box">
			<view class="bg_box">
				<image 
				:src="iconPath.positionReset"
				@click="initScaleAndTranslate" />
			</view>
			<view class="bg_box">
				<!-- <view class="chj_icon_left" :class="history_index<0?'':'active'" @click="historyEvent('回退')">
					<view></view>
					<view></view>
					<view></view>
					<view></view>
				</view> -->
				<image
				v-show="history_index<0"
				:src="iconPath.retreat_inactive"
				 />
				<image 
				v-show="!(history_index<0)"
				:src="iconPath.retreat_active"
				@click="historyEvent('回退')" />
				<!-- <view class="chj_icon_right" :class="history_index>=history_list.length-1?'':'active'" @click="historyEvent('前进')">
					<view></view>
					<view></view>
					<view></view>
					<view></view>
				</view> -->
				<image
				v-show="history_index>=history_list.length-1"
				style="margin-left: 64rpx;"
				:src="iconPath.goForward_inactive"
				 />
				<image 
				v-show="!(history_index>=history_list.length-1)"
				style="margin-left: 64rpx;"
				:src="iconPath.goForward_active"
				@click="historyEvent('前进')" />
			</view>
			<view class="bg_box">
				<!-- <view class="chj_icon_reset" @click="historyEvent('原图')">
					<view></view>
					<view></view>
				</view> -->
				<image 
				:src="iconPath.reset"
				@click="historyEvent('原图')" />
			</view>
		</view>
		<view class="canvas_box">
			<!-- <movable-area class="canvas">
				<movable-view :x="x" :y="y" :scale-value="scale" class="canvas"> -->
					<!-- <canvas
					:style="{'transform':'translate('+x+'px, '+y+'px) scale('+scale+')'}"
					class="canvas" 
					canvas-id="chj_imgEdit_canvas_save" 
					id="chj_imgEdit_canvas_save"
					/>
					<canvas
					:style="{'transform':'translate('+x+'px, '+y+'px) scale('+scale+')'}"
					class="canvas" 
					canvas-id="chj_imgEdit_canvas_bg" 
					id="chj_imgEdit_canvas_bg"
					/>
					<canvas
					:style="{'transform':'translate('+x+'px, '+y+'px) scale('+scale+')'}"
					style="z-index: 1;"
					class="canvas" 
					canvas-id="chj_imgEdit_canvas" 
					id="chj_imgEdit_canvas"
					:disable-scroll="true"
					@touchstart="touchstart"
					@touchmove="touchmove"
					@touchend="touchend"
					@touchcancel="touchend"
					/>
					<canvas
					:style="{'transform':'translate('+x+'px, '+y+'px) scale('+scale+')'}"
					style="pointer-events: none;z-index: 2;"
					class="canvas" 
					canvas-id="chj_imgEdit_canvas_text" 
					id="chj_imgEdit_canvas_text"
					/>
					<canvas
					:style="{'transform':'translate('+x+'px, '+y+'px) scale('+scale+')'}"
					style="pointer-events: none;z-index: 3;"
					class="canvas" 
					canvas-id="chj_imgEdit_canvas_hx" 
					id="chj_imgEdit_canvas_hx"
					/>
					<canvas
					style="pointer-events: none;z-index: 4;"
					class="canvas" 
					canvas-id="chj_imgEdit_canvas_cj" 
					id="chj_imgEdit_canvas_cj"
					/> -->
                    <canvas
                    :style="{'transform':'translate('+x+'px, '+y+'px) scale('+scale+')'}"
                    class="canvas" 
                    canvas-id="chj_imgEdit_canvas_save" 
                    id="chj_imgEdit_canvas_save"
                    />
                    <canvas
                    :style="{'transform':'translate('+x+'px, '+y+'px) scale('+scale+')'}"
                    class="canvas" 
                    canvas-id="chj_imgEdit_canvas_bg" 
                    id="chj_imgEdit_canvas_bg"
                    />
                    <canvas
                    :style="{'transform':'translate('+x+'px, '+y+'px) scale('+scale+')'}"
                    style="z-index: 1;"
                    class="canvas" 
                    canvas-id="chj_imgEdit_canvas" 
                    id="chj_imgEdit_canvas"
                    :disable-scroll="true"
                    @touchstart="touchstart"
                    @touchmove="touchmove"
                    @touchend="touchend"
                    @touchcancel="touchend"
                    />
                    <canvas
                    :style="{'transform':'translate('+x+'px, '+y+'px) scale('+scale+')'}"
                    style="pointer-events: none;z-index: 2;"
                    class="canvas" 
                    canvas-id="chj_imgEdit_canvas_text" 
                    id="chj_imgEdit_canvas_text"
                    />
                    <canvas
                    :style="{'transform':'translate('+x+'px, '+y+'px) scale('+scale+')'}"
                    style="pointer-events: none;z-index: 3;"
                    class="canvas" 
                    canvas-id="chj_imgEdit_canvas_hx" 
                    id="chj_imgEdit_canvas_hx"
                    />
                    <canvas
                    style="pointer-events: none;z-index: 4;"
                    class="canvas" 
                    canvas-id="chj_imgEdit_canvas_cj" 
                    id="chj_imgEdit_canvas_cj"
                    />
				<!-- </movable-view>
			</movable-area> -->
		</view>
		<!-- 涂鸦选择 -->
		<view class="tuya_box flex-row">
			<!-- 颜色选择 -->
			<view class="color_select">
				<view 
				class="item white_border" 
				v-for="(i,index) in color_list" 
				:key="index" 
				:class="{colour:i.type=='选择' && !i.color}" 
				:style="{backgroundColor:i.color,borderColor:i.id==active_color_id?activeColor:'transparent'}"
				@click="changeColor(i)">
				</view>
			</view>
			<view class="tuxing_box">
				<view class="title_box">
					<image 
					:src="iconPath.close" 
					mode="aspectFit" 
					@click="cancel"/>
					<text class="title">{{active_label}}</text>
					<image 
					:src="iconPath.confirm"
					mode="aspectFit"
					 @click="confirm"/>
				</view>
				<view class="select_box">
					<view class="num_box">
						<view class="icon" :style="tx_type_activate==='笔'?`background-color:${activeColor}`:''" @click="changeType('笔')">
							<image 
							:src="iconPath.pen" 
							mode="aspectFit" />
						</view>
						<view class="icon" :style="tx_type_activate==='橡皮'?`background-color:${activeColor}`:''" @click="changeType('橡皮')">
							<image 
							:src="iconPath.rubber" 
							mode="aspectFit" />
						</view>
						<view class="slider">
							<slider 
							:value="line_size" 
							:activeColor="activeColor" 
							:block-color="activeColor" 
							block-size="20"
							:min="1"
							:max="40"
							:step="0.2"
							@change="sliderChange"
							@changing="sliderChange"
							/>
						</view>
					</view>
					<scroll-view :show-scrollbar="false" class="tuxing_list_scroll" :scroll-y="true">
						<view class="tuxing_list">
							<view 
							class="item" 
							v-for="(i,index) in tx_list" 
							:key="index" 
							:style="i.name==tx_list_activate?`background-color:${activeColor}`:''"
							@click="listClick(i)">
								<image :src="i.icon" mode="aspectFit" />
							</view>
						</view>
					</scroll-view>
				</view>
			</view>
		</view>
		<chj-color-picker ref="chj-color-picker" :defaultColor='color' :isCover="isCover" @change="subColor" @cancel="cancelColorPicker"></chj-color-picker>
		<input 
		ref="chj_imgEdit_input"
		class="chj_imgEdit_text"
		type="text" 
		v-model="text" 
		:focus="textFocus"
		:cursor="text.length"
		:adjust-position="false"
		:auto-blur="true"
		@input="input"
		@blur="textFocus=false" />
	</view>
</view>
</template>

<script>
	// 判断鼠标是否点击到矩形的边
	function isNearEdge({x, y},rect) {
	  const margin = 20; // 判断边缘的容忍范围
	  if (Math.abs(x - rect.x) < margin) {
		rect.edge = 'left';
		return true;
	  } else if (Math.abs(x - (rect.x + rect.width)) < margin) {
		rect.edge = 'right';
		return true;
	  } else if (Math.abs(y - rect.y) < margin) {
		rect.edge = 'top';
		return true;
	  } else if (Math.abs(y - (rect.y + rect.height)) < margin) {
		rect.edge = 'bottom';
		return true;
	  }
	  return false;
	}
	let initialTouches = []; // 初始触摸点
	let initialDistance = 0;  // 初始距离
	let initialCenter = { x: 0, y: 0 }; // 初始中心点
	// 是否两指操作
	let isTowTouch = false;
	// 计算两点之间的距离
	function getDistance(touch1, touch2) {
	    const dx = touch2.x - touch1.x;
	    const dy = touch2.y - touch1.y;
	    return Math.sqrt(dx * dx + dy * dy); // 使用勾股定理计算距离
	}
	
	// 计算两触摸点的中心点
	function getCenter(touch1, touch2) {
	    return {
	        x: (touch1.x + touch2.x) / 2,
	        y: (touch1.y + touch2.y) / 2
	    };
	}
	// 判断触摸事件是平移还是放大/缩小
	function checkTouchOperation(startTouches, currentTouches) {
        
        console.log('4-1',startTouches,currentTouches)
	    const startDistance = getDistance(startTouches[0], startTouches[1]);
	    const currentDistance = getDistance(currentTouches[0], currentTouches[1]);
	
	    const startCenter = getCenter(startTouches[0], startTouches[1]);
	    const currentCenter = getCenter(currentTouches[0], currentTouches[1]);
        console.log('currentDistance ， startDistance',currentDistance , startDistance,startCenter,currentCenter)
	    // 判断是否为放大/缩小操作
		if (Math.abs(currentDistance - startDistance) > 50) {  // 距离变化超过10像素，认为是放大或缩小
			// 倍率
			const scale = 0.001;
			if (currentDistance > startDistance) {
				return {type:'放大',scale:(currentDistance - startDistance)*scale};
			} else {
				return {type:'缩小',scale:(currentDistance - startDistance)*scale};
			}
		} else {
			// 判断是否为平移操作
			const moveDistance = {
				x: currentCenter.x - startCenter.x,
				y: currentCenter.y - startCenter.y
			};
            console.log('4-2',moveDistance)
			return {type:'移动',x:moveDistance.x,y:moveDistance.y};
		}
		
	}
	function preventScroll(e) {
		e.preventDefault(); // 阻止触摸滚动
	};
	export default {
		props:{
			// 激活的颜色
			activeColor:{
				type:String,
				default:'#FFCC33'
			}
		},
		data() {
			return {
				// 缩放倍率
				scale:1,
				// 偏移量
				x:0,
				y:0,
				// 是否在取消时提示
				isCancelToast: true,
				// 取消提示内容
				cancelText: '内容未保存，确定退出吗？',
				// 是否在确定时提示
				isConfirmToast: true,
				// 确定提示内容
				confirmText: '确定完成编辑吗？',
				show:false,
				path:'',
				// 是否被覆盖
				isCover:false,
				// 操作list
				tx_list:[
					{
						name:"画笔",
						label:"画笔",
						icon:``
					},
					{
						name:"矩形",
						label:"矩形",
						icon:``
					},
					// {
					// 	name:"圆形",
					// 	label:"圆形",
					// 	icon:``
					// },
					// {
					// 	name:"横线",
					// 	label:"直线",
					// 	icon:``
					// },
					{
						name:"箭头",
						label:"箭头",
						icon:``
					},
					{
						name:"文本",
						label:"文本",
						icon:``
					},
					// {
					// 	name:"裁剪",
					// 	label:"裁剪",
					// 	icon:``
					// },
					// {
					// 	name:"翻转",
					// 	label:"翻转",
					// 	icon:``
					// }
				],
				// 当前激活的操作
				tx_list_activate:'画笔',
				// 当前激活的是笔还是橡皮
				tx_type_activate:'笔',
				// 主要绘画canvas上下文对象
				ctx:null,
				// 背景canvas上下文对象
				ctx_bg:null,
				// 回显canvas
				ctx_hx:null,
				// 文本canvas
				ctx_text:null,
				// 保存canvas
				ctx_save:null,
				// 裁剪canvas
				ctx_cj:null,
				// 裁剪数据
				cj_data:{
					x:0,
					y:0,
					width:0,
					height:0,
					dragging: false, // 是否在拖动
					edge: null, // 当前拖动的边
				},
                
				// 笔或橡皮的大小
                line_size:4,
				pen_size:4,
                // 输入框字体大小
                text_size:14,
				// 选择的颜色
				color:'#ff0000',
				// 当前笔的颜色
				pan_color:'#000',
				// 绘画历史记录
				history_list:[],
				// 历史记录指针，记录当前是第几步
				history_index:-1,
				// 颜色list
				color_list:[
					{id:'1',type:'默认',color:'#000'},
					{id:'2',type:'默认',color:'#fff'},
					{id:'3',type:'默认',color:'#ff0000'},
					{id:'4',type:'默认',color:'#ffaa00'},
					{id:'5',type:'默认',color:'#00aa00'},
					{id:'6',type:'默认',color:'#0055ff'},
					{id:'7',type:'默认',color:'#aa00ff'},
					{id:'8',type:'选择',color:''},
				],
				// 选中的颜色
				active_color_id:'1',
				// 落笔的位置
				moveTo:{x:0,y:0},
				// 插入文本
				text:'点击输入文字',
				// 画箭头的长度
				headlen:20,
				// 文本list
				textList:[],
				// 是否唤起键盘
				textFocus:false,
				// 图标
				iconPath:{
					// 复位
					positionReset:``,
					// 前进可点击状态
					goForward_active:``,
					// 前进不可点击状态
					goForward_inactive:``,
					// 后退可点击状态
					retreat_active:``,
					// 后退不可点击状态
					retreat_inactive:``,
					// 重置
					reset:``,
					// 取消
					close:``,
					// 确定
					confirm:``,
					// 笔
					pen:``,
					// 橡皮
					rubber:``,
				},
				// 旋转角度
				degrees:0,
			}
		},
		mounted() {
			// #ifdef H5
			const element = document.getElementsByClassName('chj_imgEdit')[0];
			element.style.height = window.innerHeight + 'px';
			// #endif
			// #ifdef MP-WEIXIN
			this.isCover = true;
			// #endif
		},
		methods: {
			open(options){
				// 底图路径
				this.path = options.path || '';
				// 是否在取消时提示
				this.isCancelToast = options.isCancelToast===undefined?true:options.isCancelToast;
				// 是否在确定时提示
				this.isConfirmToast = options.isConfirmToast===undefined?true:options.isConfirmToast;;
				// 退出提示内容
				this.cancelText = options.cancelText || '内容未保存，确定退出吗？';
				// 确定提示内容
				this.confirmText = options.confirmText || '确定完成编辑吗？';
				this.initScaleAndTranslate();
				// 设置图标
				if(Object.prototype.toString.call(options.iconPath) === '[object Object]'){
					for (let key in options.iconPath) {
						this.iconPath[key] = options.iconPath[key];
					}
				}
				// 设置涂鸦图标
				if(Object.prototype.toString.call(options.iconPathGraffiti) === '[object Object]'){
					for (let key in options.iconPathGraffiti) {
						this.tx_list[Number(key)].icon = options.iconPathGraffiti[key];
					}
				}
				this.show = true;
				this.$nextTick(()=>{
					this.initCanvas();
				});
			},
			// 确定
			async confirm(){
				if(this.tx_list_activate=='裁剪'){
					const isCj = await this.showModal(true,'确定裁剪吗？');
					if(isCj){
						await this.cjExecute();
					}
					this.ctx_cj.clearRect(0,0,10000,10000);
					this.ctx_cj.draw();
					this.tx_list_activate = '画笔';
					return;
				}
				const is = await this.showModal(this.isConfirmToast,this.confirmText);
				if(is){
					this.initScaleAndTranslate();
					this.ctx_save.clearRect(0,0,10000,10000);
					this.ctx_save.draw();
					this.$nextTick(async()=>{
						uni.showLoading({
							title: '加载中',
							mask:true
						});
						// 拿到文本canvas的图片路径
						this.textList = this.textList.map(i=>({...i,isActive:false}));
						this.drawText();
						// 画canvas
						const path = await this.canvasGetImagePath('chj_imgEdit_canvas_bg');
						await this.drawImageToCenter(this.ctx_save,'#chj_imgEdit_canvas_bg',path);
						const tuyaPath = await this.canvasGetImagePath('chj_imgEdit_canvas');
						await this.drawImageToCenter(this.ctx_save,'#chj_imgEdit_canvas_bg',tuyaPath);
						const textPath = await this.canvasGetImagePath('chj_imgEdit_canvas_text');
						await this.drawImageToCenter(this.ctx_save,'#chj_imgEdit_canvas_bg',textPath);
						// 拿到最终的绘画路径
						const tempFilePath = await this.canvasGetImagePath('chj_imgEdit_canvas_save');
						this.$emit('confirm',tempFilePath);
						this.show = false;
						uni.hideLoading();
						// #ifdef H5
						// 取消阻止触摸屏幕时页面滚动
						window.removeEventListener('touchmove', preventScroll, { passive: false });
						// #endif
					});
				}
			},
			// 取消
			async cancel(){
				const is = await this.showModal(this.isCancelToast,this.cancelText);
				if(is){
					this.$emit('cancel');
					this.show = false;
					// #ifdef H5
					// 取消阻止触摸屏幕时页面滚动
					window.removeEventListener('touchmove', preventScroll, { passive: false });
					// #endif
				}
			},
			// 初始化偏移量和缩放倍率
			initScaleAndTranslate(){
				// 清空缩放效率及偏移量
				this.scale = 1;
				this.x = 0;
				this.y = 0;
			},
			// 初始化canvas
			initCanvas(){
				// #ifdef H5
				// 阻止触摸屏幕时页面滚动
				window.addEventListener('touchmove', preventScroll, { passive: false });
				// #endif
				this.ctx = uni.createCanvasContext('chj_imgEdit_canvas',this); // 获取画图canvas上下文对象。
				this.ctx_bg = uni.createCanvasContext('chj_imgEdit_canvas_bg',this); // 获取背景图canvas上下文对象。
				// 初始化回显canvas
				this.ctx_hx = uni.createCanvasContext('chj_imgEdit_canvas_hx',this);
				// 初始化文本canvas
				this.ctx_text = uni.createCanvasContext('chj_imgEdit_canvas_text',this);
				// 初始化保存canvas
				this.ctx_save = uni.createCanvasContext('chj_imgEdit_canvas_save',this);
				// 裁剪canvas
				this.ctx_cj = uni.createCanvasContext('chj_imgEdit_canvas_cj',this);
				// 清空所有canvas
				this.ctx.clearRect(0,0,10000,10000);
				this.ctx_bg.clearRect(0,0,10000,10000);
				this.ctx_hx.clearRect(0,0,10000,10000);
				this.ctx_text.clearRect(0,0,10000,10000);
				this.ctx_save.clearRect(0,0,10000,10000);
				this.ctx_cj.clearRect(0,0,10000,10000);
				this.ctx.draw();
				this.ctx_bg.draw();
				this.ctx_hx.draw();
				this.ctx_text.draw();
				this.ctx_save.draw();
				this.ctx_cj.draw();
				// 当前激活的操作
				this.tx_list_activate = '画笔';
				// 当前激活的是笔还是橡皮
				this.tx_type_activate = '笔';
				// 当前笔的颜色
				this.pan_color = '#000';
				// 笔或橡皮的大小
				// this.pen_size = 10;
				// 选中的颜色
				this.active_color_id = '1';
				// 绘画历史记录
				this.history_list = [];
				// 历史记录指针，记录当前是第几步
				this.history_index = -1;
				// 文本list
				this.textList = [];
				// 设置全部样式
				this.setCanvasStyle();
				// 把背景图片画到背景canvas
				this.drawImageToCenter(this.ctx_bg,'#chj_imgEdit_canvas_bg',this.path);
			},
			// 点击操作按钮
			async listClick(item){
				if(item.name=='翻转'){
					this.drawRotatedImage();
					return;
				}
				if(this.tx_list_activate=='裁剪' && item.name!='裁剪'){
					const isCj = await this.showModal(true,'确定裁剪吗？');
					if(isCj){
						await this.cjExecute();
					}
				}
				if(item.name=='文本'){
                    this.line_size = this.text_size
					this.addText();
				}else{
                    this.line_size = this.pen_size
					this.textList = this.textList.map(i=>({...i,isActive:false}));
					this.drawText();
				}
				this.tx_list_activate = item.name;
				if(item.name=='裁剪'){
					// 获取canvas的宽高
					const {width,height} = await this.getNodeInfo('#chj_imgEdit_canvas_cj');
					// 裁剪初始范围
					const pyl = 20;
					this.cj_data = {
						x:pyl,
						y:pyl,
						width:width-(pyl*2),
						height:height-(pyl*2)
					}
					this.initScaleAndTranslate();
					this.drawCj({x:undefined,y:undefined});
				}else{
					this.ctx_cj.clearRect(0,0,10000,10000);
					this.ctx_cj.draw();
				}
			},
			// 绘制翻转背景
			drawRotatedImage(){
				this.initScaleAndTranslate();
				this.$nextTick(async()=>{
					// 1. 获取图片信息（宽高）
					const {width:imgWidth,height:imgHeight} = await this.imgInfo(this.path);
					const {width:canvasWidth,height:canvasHeight} = await this.getNodeInfo('#chj_imgEdit_canvas_bg');
					this.degrees+=90;
					if(this.degrees>270){
						this.degrees = 0;
					}
					this.ctx_bg.save();
					// 移动到画布中心
					this.ctx_bg.translate(canvasWidth / 2, canvasHeight / 2);
					// 转换为弧度并旋转
					const radians = this.degrees * Math.PI / 180;
					this.ctx_bg.rotate(radians);
					// 计算旋转后的虚拟尺寸
					let rotatedWidth, rotatedHeight;
					if (this.degrees % 180 === 0) {
						rotatedWidth = imgWidth;
						rotatedHeight = imgHeight;
					} else {
						rotatedWidth = imgHeight;
						rotatedHeight = imgWidth;
					}
					// 计算适应画布的最大缩放比例
					const scaleX = canvasWidth / rotatedWidth;
					const scaleY = canvasHeight / rotatedHeight;
					const scale = Math.min(scaleX, scaleY); // 取较小值保证完整显示
					// 应用缩放
					this.ctx_bg.scale(scale, scale);
					// 计算绘制位置（始终居中）
					const dx = -imgWidth / 2;
					const dy = -imgHeight / 2;
					// 绘制图片
					this.ctx_bg.drawImage(this.path, dx, dy, imgWidth, imgHeight);
					this.ctx_bg.restore();
					this.ctx_bg.draw(); // 强制重绘
				})
			},
			// 执行裁剪
			async cjExecute(){
				uni.showLoading({
					title: '加载中',
					mask:true
				});
				this.textList = this.textList.map(i=>({...i,isActive:false}));
				this.drawText();
				// 画canvas
				const path = await this.canvasGetImagePath('chj_imgEdit_canvas_bg');
				await this.drawImageToCenter(this.ctx_save,'#chj_imgEdit_canvas_bg',path);
				const tuyaPath = await this.canvasGetImagePath('chj_imgEdit_canvas');
				await this.drawImageToCenter(this.ctx_save,'#chj_imgEdit_canvas_bg',tuyaPath);
				const textPath = await this.canvasGetImagePath('chj_imgEdit_canvas_text');
				await this.drawImageToCenter(this.ctx_save,'#chj_imgEdit_canvas_bg',textPath);
				// 拿到最终的绘画路径
				const tempFilePath = await this.canvasGetImagePath('chj_imgEdit_canvas_save',this.cj_data);
				await this.clearCanvas(this.ctx_bg);
				await this.clearCanvas(this.ctx);
				await this.clearCanvas(this.ctx_save);
				await this.drawImageToCenter(this.ctx_bg,'#chj_imgEdit_canvas_bg',tempFilePath,false);
				this.textList = [];
				this.drawText();
				this.history_list = [];
				this.history_index = -1;
				uni.hideLoading();
			},
			// 手指触摸动作开始
			touchstart(e){
				if(Object.prototype.toString.call(e.touches) === '[object Object]'){
					if(e.touches[1]){
						e.touches = [e.touches[0],e.touches[1]];
					}else{
						e.touches = [e.touches[0]];
					}
				}
				if (e.touches.length === 2 && this.tx_list_activate!='裁剪') {
					initialTouches = [
						{ x: e.touches[0].x, y: e.touches[0].y },
						{ x: e.touches[1].x, y: e.touches[1].y }
					];
					initialDistance = getDistance(initialTouches[0], initialTouches[1]);
					initialCenter = getCenter(initialTouches[0], initialTouches[1]);
					// 是否是两指操作
					isTowTouch = true;
					return;
				}
				e.touches[0].x /= this.scale;
				e.touches[0].y /= this.scale;
				// 判断点击的是哪条边
				if (isNearEdge(e.touches[0],this.cj_data)) {
					this.cj_data.dragging = true;
				}
				// 画图
				this.moveTo = {x:e.touches[0].x,y:e.touches[0].y};
				if(this.tx_list_activate=='画笔') this.ctx.moveTo(this.moveTo.x,this.moveTo.y);
				// 画线
				// this.drawLine(e.touches[0]);
				// 画矩形回显
				this.drawRectHX(e.touches[0]);
				// 画橡皮回显
				this.drawEraserHX(e.touches[0]);
				// 画圆回显
				this.drawCircleHX(e.touches[0]);
				// 画横线回显
				this.drawHorizontalLineHX(e.touches[0]);
				// 画箭头回显
				this.drawAarrowHX(e.touches[0]);
				// 文本点击事件
				this.isInAreaClick(e.touches[0]);
			},
			// 手指触摸后移动
			touchmove(e){
                let moving = true
                console.log(isTowTouch,'手指触摸后移动',e,this.tx_list_activate)
				if(e.touches[0].x==undefined && e.touches[0].y==undefined){
					e.touches[0].x = e.touches[0].clientX;
					e.touches[0].y = e.touches[0].clientY;
				}
                let that = this
				if (isTowTouch && this.tx_list_activate!='裁剪') {
                    moving = false
                    console.log('2')
                    //this.scale += 0.01
					if(Object.prototype.toString.call(e.touches) === '[object Object]'){
						if(e.touches[1]){
							e.touches = [e.touches[0],e.touches[1]];
						}else{
							e.touches = [e.touches[0]];
						}
					}
					if (e.touches.length === 2){
                        console.log('3')
						if(e.touches[1].x==undefined && e.touches[1].y==undefined){
							e.touches[1].x = e.touches[1].clientX;
							e.touches[1].y = e.touches[1].clientY;
						}
						const currentTouches = [
							{ x: e.touches[0].x, y: e.touches[0].y },
							{ x: e.touches[1].x, y: e.touches[1].y }
						];
						const obj = checkTouchOperation(initialTouches, currentTouches);
                        console.log('51',obj,that.scale)
						// if(obj.type=='放大'){
      //                       console.log('52',that.scale,that.scale>10)
						// 	if(that.scale>10) return;
						// 	that.scale += 0.02//obj.scale;
      //                       // 把背景图片画到背景canvas
      //                       this.drawImageToCenter(this.ctx_bg,'#chj_imgEdit_canvas_bg',this.path);
						// }else if(obj.type=='缩小'){
      //                       console.log('6')
						// 	if(that.scale<0.5) return;
						// 	that.scale += -0.02;
      //                       this.drawImageToCenter(this.ctx_bg,'#chj_imgEdit_canvas_bg',this.path);
						// }
      //                   else 
                        if(obj.type=='移动'){
                            console.log('7')
							that.x += obj.x;
							that.y += obj.y;
						}
                        that.$forceUpdate()
						return;
					}
				}
                if(!moving){
                    return false
                }
				e.touches[0].x /= that.scale;
				e.touches[0].y /= that.scale;
                console.log('eeeee',e)
                console.log('that.scale',that.scale,that.x,that.y)
                
				// 画线回显
				this.drawLine(e.touches[0]);
				// 画矩形回显
				this.drawRectHX(e.touches[0]);
				// 画橡皮回显
				this.drawEraserHX(e.touches[0]);
				// 画圆回显
				this.drawCircleHX(e.touches[0]);
				// 画横线回显
				this.drawHorizontalLineHX(e.touches[0]);
				// 画箭头回显
				this.drawAarrowHX(e.touches[0]);
				// 文本移动事件
				this.isInAreaMove(e.touches[0]);
				// 裁剪
				this.drawCj(e.touches[0]);
			},
			// 手指触摸动作结束
			touchend(e){
                console.log('end:::',e)
				if(this.tx_list_activate=='裁剪'){
					this.cj_data.dragging = false;
					return;
				} 
				if (isTowTouch && this.tx_list_activate!='裁剪') {
					initialTouches = []; // 初始触摸点
					initialDistance = 0;  // 初始距离
					initialCenter = { x: 0, y: 0 }; // 初始中心点
					const time = setTimeout(()=>{
						isTowTouch = false;
						clearTimeout(time);
					},50);
					return;
				}
				if(e.changedTouches[0].x==undefined && e.changedTouches[0].y==undefined){
					e.changedTouches[0].x = e.changedTouches[0].clientX;
					e.changedTouches[0].y = e.changedTouches[0].clientY;
				}
				e.changedTouches[0].x /= this.scale;
				e.changedTouches[0].y /= this.scale;
				this.ctx.draw(true);
				// 清空回显canvas
				this.ctx_hx.clearRect(0,0,10000,10000);
				this.ctx_hx.draw();
				// 圆形
				this.drawCircle(e.changedTouches[0]);
				// 矩形
				this.drawRect(e.changedTouches[0]);
				// 横线
				this.drawHorizontalLine(e.changedTouches[0]);
				// 箭头
				this.drawAarrow(e.changedTouches[0]);
				// 保存绘画记录
				this.save();
			},
			// 获取触摸的颜色
			getColorRGBA({x,y}){
				return new Promise((resolve,reject)=>{
					const imgData = uni.canvasGetImageData({
						canvasId:'chj_imgEdit_canvas_bg',
						x,
						y,
						width: x+1,
						height: y+1,
						success: (res) => {
							resolve({
								R:res.data[0],
								G:res.data[1],
								B:res.data[2],
								A:res.data[3],
							});
						}
					}, this);
				})
			},
			// 画线方法
			drawLine({x,y}){
				if(this.tx_list_activate!='画笔' && this.tx_type_activate!='橡皮') return;
				// #ifdef MP-WEIXIN
				if(this.tx_type_activate!='橡皮'){
					this.setCanvasStyle();
					this.ctx.lineTo(x,y);
					this.ctx.stroke();
					this.ctx.draw(true);
					this.ctx.moveTo(x,y);
				}
				// #endif
				// #ifndef MP-WEIXIN
				this.setCanvasStyle();
				this.ctx.lineTo(x,y);
				this.ctx.stroke();
				this.ctx.draw(true);
				this.ctx.moveTo(x,y);
				// #endif
			},
			// 画矩形
			drawRect({x,y}){
				if(this.tx_list_activate!='矩形' || this.tx_type_activate=='橡皮') return;
				let width,heigth;
				let dx,dy;
				if(this.moveTo.x>x){
					dx = x;
					width = this.moveTo.x - x;
				}else{
					dx = this.moveTo.x;
					width = x - this.moveTo.x;
				}
				if(this.moveTo.y>y){
					dy = y;
					heigth = this.moveTo.y - y;
				}else{
					dy = this.moveTo.y;
					heigth = y - this.moveTo.y;
				}
				this.setCanvasStyle();
				this.ctx.rect(dx,dy,width,heigth);
				this.ctx.stroke();
				this.ctx.draw(true);
			},
			// 回显画矩形
			drawRectHX({x,y}){
				if(this.tx_list_activate!='矩形' || this.tx_type_activate=='橡皮') return;
				let width,heigth;
				let dx,dy;
				if(this.moveTo.x>x){
					dx = x;
					width = this.moveTo.x - x;
				}else{
					dx = this.moveTo.x;
					width = x - this.moveTo.x;
				}
				if(this.moveTo.y>y){
					dy = y;
					heigth = this.moveTo.y - y;
				}else{
					dy = this.moveTo.y;
					heigth = y - this.moveTo.y;
				}
				this.setCanvasStyle();
				this.ctx_hx.rect(dx,dy,width,heigth);
				this.ctx_hx.stroke();
				this.ctx_hx.draw();
			},
			// 画圆
			drawCircle({x,y}){
				if(this.tx_list_activate!='圆形' || this.tx_type_activate=='橡皮') return;
				let width,heigth;
				let dx,dy;
				if(this.moveTo.x>x){
					width = this.moveTo.x - x;
					dx = x + (width/2);
				}else{
					width = x - this.moveTo.x;
					dx = this.moveTo.x + (width/2);
				}
				if(this.moveTo.y>y){
					heigth = this.moveTo.y - y;
					dy = y + (heigth/2);
				}else{
					heigth = y - this.moveTo.y;
					dy = this.moveTo.y + (heigth/2);
				}
				// 半径
				const r = width>heigth?width/2:heigth/2;
				this.setCanvasStyle();
				this.ctx.arc(dx,dy,r,0,2*Math.PI);
				this.ctx.stroke();
				this.ctx.draw(true);
			},
			// 回显画圆
			drawCircleHX({x,y}){
				if(this.tx_list_activate!='圆形' || this.tx_type_activate=='橡皮') return;
				let width,heigth;
				let dx,dy;
				if(this.moveTo.x>x){
					width = this.moveTo.x - x;
					dx = x + (width/2);
				}else{
					width = x - this.moveTo.x;
					dx = this.moveTo.x + (width/2);
				}
				if(this.moveTo.y>y){
					heigth = this.moveTo.y - y;
					dy = y + (heigth/2);
				}else{
					heigth = y - this.moveTo.y;
					dy = this.moveTo.y + (heigth/2);
				}
				// 半径
				const r = width>heigth?width/2:heigth/2;
				this.setCanvasStyle();
				this.ctx_hx.arc(dx,dy,r,0,2*Math.PI);
				this.ctx_hx.stroke();
				this.ctx_hx.draw();
			},
			// 画横线
			drawHorizontalLine({x,y}){
				if(this.tx_list_activate!='横线' || this.tx_type_activate=='橡皮') return;
				this.setCanvasStyle();
				this.ctx.moveTo(this.moveTo.x,this.moveTo.y);
				this.ctx.lineTo(x,y);
				this.ctx.stroke();
				this.ctx.draw(true);
				// 横线的长度 单位px
				const len = getDistance({x:this.moveTo.x,y:this.moveTo.y},{x,y}) * this.scale;
				this.$emit('getLineLength',len);
			},
			// 回显画横线
			drawHorizontalLineHX({x,y}){
				if(this.tx_list_activate!='横线' || this.tx_type_activate=='橡皮') return;
				this.setCanvasStyle();
				this.ctx_hx.moveTo(this.moveTo.x,this.moveTo.y);
				this.ctx_hx.lineTo(x,y);
				this.ctx_hx.stroke();
				this.ctx_hx.draw();
			},
			// 画箭头
			drawAarrow({x,y}){
				if(this.tx_list_activate!='箭头' || this.tx_type_activate=='橡皮') return;
				this.setCanvasStyle();
				this.ctx.moveTo(this.moveTo.x,this.moveTo.y);
				this.ctx.lineTo(x,y);
				// 绘制箭头
				const angle = Math.atan2(y - this.moveTo.y, x - this.moveTo.x); // 计算角度
				this.ctx.lineTo(x - this.headlen * Math.cos(angle - Math.PI / 6), y - this.headlen * Math.sin(angle - Math.PI / 6));
				this.ctx.moveTo(x, y);
				this.ctx.lineTo(x - this.headlen * Math.cos(angle + Math.PI / 6), y - this.headlen * Math.sin(angle + Math.PI / 6));
				this.ctx.stroke();
				this.ctx.draw(true);
			},
			// 回显画箭头
			drawAarrowHX({x,y}){
				if(this.tx_list_activate!='箭头' || this.tx_type_activate=='橡皮') return;
				this.setCanvasStyle();
				this.ctx_hx.moveTo(this.moveTo.x,this.moveTo.y);
				this.ctx_hx.lineTo(x,y);
				// 绘制箭头
				const angle = Math.atan2(y - this.moveTo.y, x - this.moveTo.x); // 计算角度
				this.ctx_hx.lineTo(x - this.headlen * Math.cos(angle - Math.PI / 6), y - this.headlen * Math.sin(angle - Math.PI / 6));
				this.ctx_hx.moveTo(x, y);
				this.ctx_hx.lineTo(x - this.headlen * Math.cos(angle + Math.PI / 6), y - this.headlen * Math.sin(angle + Math.PI / 6));
				this.ctx_hx.stroke();
				this.ctx_hx.draw();
			},
			// 添加文本
			async addText(){
				this.text = "点击输入文字";
				// 获取canvas的宽高
				const {width,height} = await this.getNodeInfo('#chj_imgEdit_canvas_text');
				// 计算文本的宽度
				this.ctx_text.setFontSize(this.text_size);
				const {width:textWidth} = this.ctx_text.measureText(this.text);
				this.textList = this.textList.map(i=>({...i,isActive:false}));
				this.textList.unshift({
					text:this.text,
					isActive:true,
					x:width/2,	// 中心点的定位x
					y:height/2,	// 中心点的定位y
					zIndex:1,	//层级，1为优先级高的
					textWidth,
					fontSize:this.text_size,
					width:textWidth+20,
					height:this.text_size+20,
					fontColor:this.pan_color,
					// 删除按钮的半径
					arcSize:10,
				});
				this.drawText();
			},
			// 画出文本的位置
			drawText(){
				// 先清空画布
				this.ctx_text.clearRect(0,0,10000,10000);
				// 删除没有内容的文本
				this.textList = this.textList.filter((i)=>i.text||i.isActive);
				for (let i of this.textList) {
					if(i.isActive){
						this.ctx_text.setStrokeStyle('#fff');
						this.ctx_text.strokeRect(i.x - i.width/2, i.y - i.height/2, i.width, i.height);
						// 画×
						const arcX = i.x-i.width/2;
						const arcY = i.y-i.height/2;
						this.ctx_text.arc(arcX, arcY, i.arcSize, 0, 2 * Math.PI);
						this.ctx_text.setFillStyle('#EEEEEE');
						this.ctx_text.fill();
						this.ctx_text.beginPath();
						this.ctx_text.moveTo(arcX-i.arcSize/2, arcY-i.arcSize/2);
						this.ctx_text.lineTo(arcX+i.arcSize/2, arcY+i.arcSize/2);
						this.ctx_text.moveTo(arcX+i.arcSize/2, arcY-i.arcSize/2);
						this.ctx_text.lineTo(arcX-i.arcSize/2, arcY+i.arcSize/2);
						this.ctx_text.setStrokeStyle('#000');
						this.ctx_text.stroke();
					}
					this.ctx_text.setFontSize(i.fontSize);
					this.ctx_text.setTextBaseline('middle');
					this.ctx_text.setFillStyle(i.fontColor);
					this.ctx_text.fillText(i.text,i.x - i.textWidth/2, i.y, i.textWidth);
				}
				this.ctx_text.draw();
			},
			// 画出裁剪框
			drawCj({x,y}){
				if(this.tx_list_activate=='裁剪'){
					if (this.cj_data.dragging) {
						const dx = x - this.moveTo.x;
						const dy = y - this.moveTo.y;
						this.moveTo = {x,y};
						// 根据拖动的边，调整矩形
						if (this.cj_data.edge === 'left') {
						  this.cj_data.x += dx;
						  this.cj_data.width -= dx;
						} else if (this.cj_data.edge === 'right') {
						  this.cj_data.width += dx;
						} else if (this.cj_data.edge === 'top') {
						  this.cj_data.y += dy;
						  this.cj_data.height -= dy;
						} else if (this.cj_data.edge === 'bottom') {
						  this.cj_data.height += dy;
						}
					}
					this.ctx_cj.setLineWidth(5);
					this.ctx_cj.rect(this.cj_data.x, this.cj_data.y, this.cj_data.width, this.cj_data.height);
					this.ctx_cj.setStrokeStyle(this.activeColor);
					// 画出可缩放提示框
					const length = 20;
					const distance = 7;
					this.ctx_cj.moveTo(this.cj_data.x+length,this.cj_data.y-distance);
					this.ctx_cj.lineTo(this.cj_data.x-distance,this.cj_data.y-distance);
					this.ctx_cj.lineTo(this.cj_data.x-distance,this.cj_data.y+length);
					this.ctx_cj.moveTo((this.cj_data.width/2)+this.cj_data.x-length,this.cj_data.y-distance);
					this.ctx_cj.lineTo((this.cj_data.width/2)+this.cj_data.x+length,this.cj_data.y-distance);
					
					this.ctx_cj.moveTo(this.cj_data.width+this.cj_data.x-length,this.cj_data.y-distance);
					this.ctx_cj.lineTo(this.cj_data.width+this.cj_data.x+distance,this.cj_data.y-distance);
					this.ctx_cj.lineTo(this.cj_data.width+this.cj_data.x+distance,this.cj_data.y+length);
					this.ctx_cj.moveTo(this.cj_data.width+this.cj_data.x+distance,(this.cj_data.height/2)+this.cj_data.y-length);
					this.ctx_cj.lineTo(this.cj_data.width+this.cj_data.x+distance,(this.cj_data.height/2)+this.cj_data.y+length);
					
					this.ctx_cj.moveTo(this.cj_data.width+this.cj_data.x+distance,this.cj_data.height+this.cj_data.y-length);
					this.ctx_cj.lineTo(this.cj_data.width+this.cj_data.x+distance,this.cj_data.height+this.cj_data.y+distance);
					this.ctx_cj.lineTo(this.cj_data.width+this.cj_data.x-length,this.cj_data.height+this.cj_data.y+distance);
					this.ctx_cj.moveTo((this.cj_data.width/2)+this.cj_data.x-length,this.cj_data.height+this.cj_data.y+distance);
					this.ctx_cj.lineTo((this.cj_data.width/2)+this.cj_data.x+length,this.cj_data.height+this.cj_data.y+distance);
					
					this.ctx_cj.moveTo(this.cj_data.x-distance,this.cj_data.height+this.cj_data.y-length);
					this.ctx_cj.lineTo(this.cj_data.x-distance,this.cj_data.height+this.cj_data.y+distance);
					this.ctx_cj.lineTo(this.cj_data.x+length,this.cj_data.height+this.cj_data.y+distance);
					this.ctx_cj.moveTo(this.cj_data.x-distance,(this.cj_data.height/2)+this.cj_data.y-length);
					this.ctx_cj.lineTo(this.cj_data.x-distance,(this.cj_data.height/2)+this.cj_data.y+length);
					this.ctx_cj.stroke();
					this.ctx_cj.draw();
				}
			},
			// 画出中心的标记线
			drawCenterLine(ctx,x,y){
				ctx.setStrokeStyle('red');
				ctx.moveTo(0, y)
				ctx.lineTo(10000, y)
				ctx.moveTo(x, 0)
				ctx.lineTo(x, 10000)
				ctx.stroke()
				ctx.draw()
			},
			// 点击范围内的文字操作
			isInAreaClick({x,y}){
				if(this.tx_list_activate != '文本' || this.tx_type_activate=='橡皮') return;
				// 检查是否点击在范围内
				for (let index in this.textList) {
					const item = this.textList[index];
					const arcX = item.x-item.width/2;
					const arcY = item.y-item.height/2;
					if(item.isActive && x >= arcX-item.arcSize && x <= arcX-item.arcSize + item.arcSize*2 &&
						y >= arcY-item.arcSize && y <= arcY-item.arcSize + item.arcSize*2){
						// 点击的是删除按钮
						this.textList.splice(index,1);
						this.drawText();
						return;
					}
					if (
						x >= item.x-item.width/2 && x <= item.x-item.width/2 + item.width &&
						y >= item.y-item.height/2 && y <= item.y-item.height/2 + item.height
					) {
						// 点击的是文本
						if(item.isActive){
							// 唤醒输入框
							this.text = item.text;
							const time = setTimeout(()=>{
								this.textFocus = true;
								clearTimeout(time);
							},100);
							return;
						}else{
							// 选中文本
							this.textList = this.textList.map(i=>({...i,isActive:false}));
							this.textList[index].isActive = true;
							this.drawText();
							return;
						}
					}
				}
				this.textList = this.textList.map(i=>({...i,isActive:false}));
				this.drawText();
			},
			// 移动文字操作
			isInAreaMove({x,y}){
				if(this.tx_list_activate != '文本' || this.tx_type_activate=='橡皮') return;
				// 检查是否点击在范围内
				for (let index in this.textList) {
					const item = this.textList[index];
					if (
					item.isActive && x >= item.x-item.width/2 && x <= item.x-item.width/2 + item.width &&
					y >= item.y-item.height/2 && y <= item.y-item.height/2 + item.height
					) {
						this.textList[index].x += x - this.moveTo.x;
						this.textList[index].y += y - this.moveTo.y;
						this.drawText();
						this.moveTo = {x,y};
						return;
					}
				}
			},
			// 输入文本
			input(e){
				if(this.tx_list_activate != '文本') return;
				const text = e.detail.value;
				for (let index in this.textList) {
					const item = this.textList[index];
					if(item.isActive){
						// 计算文本的宽度
						this.ctx_text.setFontSize(item.fontSize);
						const {width:textWidth} = this.ctx_text.measureText(text);
						this.textList[index] = {
							...item,
							text,
							width:textWidth+20,
							height:item.fontSize+20,
							textWidth
						};
						this.drawText();
						return;
					}
				}
			},
			// 改变文本颜色
			setTextColor(color){
				if(this.tx_list_activate == '文本'){
					this.textList = this.textList.map(i=>i.isActive?{...i,fontColor:color}:i);
					this.drawText();
				}
			},
			// 改变文本大小
			setTextSize(size){
				if(this.tx_list_activate == '文本'){
					for (let index in this.textList) {
						const item = this.textList[index];
						if(item.isActive){
							// 计算文本的宽度
							this.ctx_text.setFontSize(size);
							const {width:textWidth} = this.ctx_text.measureText(item.text);
							this.textList[index] = {
								...item,
								fontSize:size,
								width:textWidth+20,
								height:size+20,
								textWidth
							};
							break;
						}
					}
					this.drawText();
				}
			},
			// 切换笔和橡皮
			changeType(type){
				if(type){
					this.tx_type_activate = type;
				}
				// #ifndef MP-WEIXIN
				// 切换橡皮或者笔
				if(this.tx_type_activate == '橡皮'){
					this.ctx.globalCompositeOperation = 'destination-out';
				}else{
					this.ctx.globalCompositeOperation = 'source-over';
				}
				// #endif
			},
			// 回显橡皮
			drawEraserHX({x,y}){
				if(this.tx_type_activate!='橡皮') return;
                this.line_size = this.pen_size
				// #ifdef MP-WEIXIN
				this.ctx.clearRect(x-this.line_size/2,y-this.line_size/2,this.line_size,this.line_size);
				this.ctx.draw(true);
				this.ctx_hx.setFillStyle('#fff');
				this.ctx_hx.fillRect(x-this.line_size/2,y-this.line_size/2,this.line_size,this.line_size);
				this.ctx_hx.draw();
				// #endif
				// #ifndef MP-WEIXIN
				this.ctx_hx.setFillStyle('#fff');
				this.ctx_hx.arc(x,y,this.line_size/2,0,Math.PI*2);
				this.ctx_hx.fill();
				this.ctx_hx.draw();
				// #endif
			},
			// 切换笔的颜色
			changeColor(item){
				if(item.type!='选择'){
					this.color_list[7].color = '';
				}
				this.active_color_id = item.id;
				if(item.type=='选择') return this.$refs['chj-color-picker'].open();
				this.pan_color = item.color;
				this.setStrokeStyle();
			},
			// 确定选中颜色
			subColor({rgba:{R,G,B,A},hex}){
				this.pan_color = `rgba(${R},${G},${B},${A})`;
				this.color = hex;
				this.color_list[7].color = this.pan_color;
				this.setStrokeStyle();
			},
			// 取消颜色选择
			cancelColorPicker(){
				const obj = this.color_list.find(i=>i.color==this.pan_color);
				this.active_color_id = obj.id;
			},
			// 设置canvas笔的颜色
			setStrokeStyle(){
				this.ctx.setStrokeStyle(this.pan_color);
				// 把回显canvas也设置了
				this.ctx_hx.setStrokeStyle(this.pan_color);
				this.setTextColor(this.pan_color);
			},
			// 滑动选择笔的粗细
			sliderChange(e){
                console.log('this.tx_list_activate',this.tx_list_activate,e)
				if (e) {
                    if(this.tx_list_activate=='文本'){
                        this.text_size = e.detail.value;
                    }else{
                        this.pen_size = e.detail.value;
                    }
				}
				this.ctx.setLineWidth(this.pen_size);
				this.ctx.setLineJoin('round');
				this.ctx.setLineCap('round');
				// 把回显canvas也设置了
				this.ctx_hx.setLineWidth(this.pen_size);
				this.ctx_hx.setLineJoin('round');
				this.ctx_hx.setLineCap('round');
				// 设置文本大小
				this.setTextSize(this.pen_size);
			},
			// 设置canvas画图所有的样式
			setCanvasStyle(){
				this.setStrokeStyle();
				this.sliderChange();
				this.changeType();
			},
			// 获取图片的参数
			imgInfo(src){
				return new Promise((res,rej)=>{
					uni.getImageInfo({
						src,
						success(data){
							res(data);
						},
						fail(err){
							rej(err);
						}
					})
				})
			},
			// 已知图片的宽高和canvas的宽高，将图片缩放绘制到中心
			drawImageToCenter(ctx,selector,path,reserve=true){
				return new Promise(async (resolve,reject)=>{
					// 获取图片的宽高
					const {width,height} = await this.imgInfo(path);
					// 获取canvas的宽高
					const {width:canvasWidth,height:canvasHeight} = await this.getNodeInfo(selector);
					let dx,dy,dWidth,dHeight;
					if(width>=height){
						dx = 0;
						dWidth = canvasWidth;
						// 按照比例计算高度
						dHeight = canvasWidth / width * height;
						dy = (canvasHeight - dHeight) / 2;
					}else{
						dy = 0;
						dHeight = canvasHeight;
						// 按照比例计算宽度
						dWidth = canvasHeight / height * width;
						dx = (canvasWidth - dWidth) / 2;
					}
					ctx.drawImage(path, dx, dy, dWidth, dHeight);
					ctx.draw(reserve,()=>{
						resolve();
					});
				})
				
			},
			// 获取节点的信息（宽高）
			getNodeInfo(selector){
				return new Promise((res,rej)=>{
					uni.createSelectorQuery().in(this).select(selector).fields({
						size:true
					},(data)=>{
						res(data);
					}).exec();
				})
			},
			// 保存当前绘制内容
			async save(){
				if(this.tx_list_activate=='文本') return;
				// 先拿到绘画canvas的绘画图片路径
				const path = await this.canvasGetImagePath('chj_imgEdit_canvas');
				// 根据历史记录指针位置往绘画历史记录插入一条数据
				this.history_list.splice(this.history_index+1,this.history_list.length-1-this.history_index,path);
				this.history_index++;
			},
			// 获取当前绘画图片路径
			canvasGetImagePath(canvasId,range){
				return new Promise((res,rej)=>{
					if(range){
						const {x,y,width,height} = range;
						uni.canvasToTempFilePath({
							canvasId,
							x,y,width,height,
							success: function(data) {
								// 在H5平台下，tempFilePath 为 base64
								res(data.tempFilePath);
							}
						},this);
					}else{
						uni.canvasToTempFilePath({
							canvasId,
							success: function(data) {
								// 在H5平台下，tempFilePath 为 base64
								res(data.tempFilePath);
							}
						},this);
					}
				})
			},
			// 根据绘画历史记录和历史记录指针在背景canvas中画出来
			async drawBgCanvas(){
				this.initScaleAndTranslate();
				// 清空回显canvas
				this.ctx.clearRect(0,0,10000,10000);
				this.ctx.draw();
				if(this.history_index < 0) return;
				// #ifndef MP-WEIXIN
				this.ctx.globalCompositeOperation = 'source-over';
				// #endif
				// 再根据绘画历史记录画出图像
				await this.drawImageToCenter(this.ctx,'#chj_imgEdit_canvas_bg',this.history_list[this.history_index]);
				this.changeType();
			},
			// rbga转成Hex格式
			rgbaToHex(r, g, b, a) {
			  // 确保 RGB 值在 0 到 255 的范围内
			  r = Math.min(255, Math.max(0, Math.round(r)));
			  g = Math.min(255, Math.max(0, Math.round(g)));
			  b = Math.min(255, Math.max(0, Math.round(b)));
			
			  // 将 RGB 值转换为十六进制并格式化
			  const rHex = ('0' + r.toString(16)).slice(-2).toUpperCase();
			  const gHex = ('0' + g.toString(16)).slice(-2).toUpperCase();
			  const bHex = ('0' + b.toString(16)).slice(-2).toUpperCase();
			
			  // 拼接十六进制颜色代码
			  return `#${rHex}${gHex}${bHex}`;
			},
			// 前进/回退/原图 查看
			historyEvent(type){
				if (type=='回退') {
					if(this.history_index<0) return;
					this.history_index-=1;
					this.drawBgCanvas();
				}else if(type=='前进'){
					if(this.history_index>=this.history_list.length-1) return;
					this.history_index+=1;
					this.drawBgCanvas();
				}else if(type=='原图'){
					if(this.history_index>=0){
						this.history_index = -1;
						this.drawBgCanvas();
					}else{
						this.history_index = this.history_list.length-1;
						this.drawBgCanvas();
					}
				}
			},
			// 显示模态弹窗 确定/取消
			showModal(show,title){
				return new Promise((res,rej)=>{
					if(show){
						uni.showModal({
							title: '提示',
							content: title,
							success: function (data) {
								if (data.confirm) {
									res(true);
								} else if (data.cancel) {
									res(false);
								}
							}
						});
					}else{
						res(true);
					}
				});
			},
			// 清空画布
			async clearCanvas(ctx){
				new Promise((res,rej)=>{
					ctx.clearRect(0,0,10000,10000);
					ctx.draw(false,()=>{
						res();
					});
				})
			},
		},
		computed:{
			active_label(){
				const obj = this.tx_list.find(i=>i.name==this.tx_list_activate);
				return obj.label;
			},
		},
		beforeDestroy() {
			// #ifdef H5
			// 取消阻止触摸屏幕时页面滚动
			window.removeEventListener('touchmove', preventScroll, { passive: false });
			// #endif
		},
	}
	
</script>

<style lang="scss" scoped>
	// 主要颜色变量
	$color: #e5e5e5;
	.chj_imgEdit{
		// 居中混合
		.flex-center{
		  display: flex;
		  justify-content: center;
		  align-items: center;
		}
		// 纵向flex布局
		.flex-row{
			display: flex;
			flex-direction: column;
		}
		position: fixed;
		top: 0;
		left: 0;
		z-index: 998;
		display: flex;
		flex-direction: column;
		justify-content: center;
		width: 100vw;
		height: 100vh;
		overflow: hidden;
		// canvas
		.canvas_box{
			flex: 1;
			width:100%;
			background-color: $color;
			position: relative;
			overflow: hidden;
			.canvas{
				width: 100%;
				height: 100%;
				position: absolute !important;
				top: 0;
				left: 0;
			}
		}
		// 功能盒子
		.item_box{
			width: 100%;
			height: 100rpx;
			background-color: #fff;
			position: relative;
			.center_box{
				display: flex;
				flex-direction: row;
				align-items: center;
				justify-content: center;
				height: 100%;
				width: fit-content;
				min-width: 100%;
				.item{
					padding: 0 40rpx;
					width: 50rpx;
					image{
						width: 50rpx;
						height: 50rpx;
					}
					.text{
						font-size: 20rpx;
						text-align: center;
						color: #333;
						font-weight: 600;
					}
				}
			}
		}
		// 涂鸦盒子
		.tuya_box{
			width: 100%;
			// height: 30%;
			position: relative;
			// 颜色选择
			.color_select{
				box-sizing: border-box;
				width: 100%;
				display: flex;
				justify-content: space-evenly;
				background-color: #e5e5e5;
				padding: 12rpx;
				.item{
					background-clip: content-box;
					width: 32rpx;
					height: 32rpx;
					border-radius: 50%;
					border: transparent 4px solid;
					position: relative;
					@extend .flex-center;
				}
			}
			.tuxing_box{
				box-sizing: border-box;
				flex: 1;
				width: 100%;
				overflow: hidden;
				background-color: #fff;
				padding: 24rpx;
				@extend .flex-row;
				.title_box{
					display: flex;
					flex-direction: row;
					justify-content: space-between;
					image{
						width: 40rpx;
						height: 40rpx;
					}
				}
				.select_box{
					@extend .flex-row;
					flex: 1;
					padding-top: 24rpx;
					overflow: hidden;
					.num_box{
						display: flex;
						flex-direction: row;
						.icon{
							@extend .flex-center;
							background-color: $color;
							width: 82rpx;
							height: 64rpx;
							image{
								width: 38rpx;
								height: 38rpx;
							}
							&:nth-child(1){
								border-radius: 24rpx 0 0 24rpx;
							}
							&:nth-child(2){
								border-radius: 0 24rpx 24rpx 0;
								margin-left: 8rpx;
							}
						}
						.slider{
							flex: 1;
						}
					}
					.tuxing_list_scroll{
						flex: 1;
						overflow: hidden;
						padding-top: 12rpx;
						.tuxing_list{
							display: flex;
							flex-direction: row;
							flex-wrap: wrap;
							.item{
								margin-top: 12rpx;
								box-sizing: border-box;
								@extend .flex-center;
								width: calc(25% - 19rpx);
								height: 84rpx;
								margin-right: 24rpx;
								border-radius: 24rpx;
								background-color: $color;
								image{
									height: calc(100% - 24rpx);
								}
								&:nth-child(4n){
									margin-right: 0;
								}
							}
						}
					}
				}
			}
			
		}
		// 彩球
		.colour{
			background-image: linear-gradient(45deg,red,transparent),linear-gradient(90deg,orange,transparent),linear-gradient(135deg,yellow,transparent),linear-gradient(-135deg,green,transparent),linear-gradient(-90deg,aquamarine,transparent),linear-gradient(-45deg,blue,transparent);
		}
		.white_border::after{
			content: '';
			position: absolute;
			width: 100%;
			height: 100%;
			border: 2rpx solid #fff;
			border-radius: 50%;
		}
	}
	.chj_imgEdit_text{
		position: absolute;
		left: -1000px;
	}
	.history_box{
		padding: 24rpx 0;
		width: 100%;
		z-index: 5;
		background-color: $color;
		@extend .flex-center;
		.bg_box{
			background-color: #56565624;
			border-radius: 24rpx;
			&:nth-child(1){
				position: absolute;
				left: 48rpx;
				padding: 12rpx;
			}
			&:nth-child(2){
				padding: 12rpx 24rpx;
			}
			&:nth-child(3){
				position: absolute;
				right: 48rpx;
				padding: 12rpx;
			}
			@extend .flex-center;
		}
		image{
			width: 48rpx;
			height: 48rpx;
		}
		.chj_icon_left{
			position: relative;
			width: 48rpx;
			height: 48rpx;
			@extend .flex-center;
			cover-view,view{
				position: absolute;
				border-radius: 4rpx;
				background-color: #8a8a8a;
				&:nth-child(1){
					top: 30%;
					left: 2%;
					width: 25%;
					height: 4rpx;
					transform: rotate(50deg);
				}
				&:nth-child(2){
					top: 19%;
					left: 2%;
					width: 25%;
					height: 4rpx;
					transform: rotate(-50deg);
				}
				&:nth-child(3){
					width: 50%;
					height: 4rpx;
					top: 25%;
					left: 10%;
				}
				&:nth-child(4){
					width: 50%;
					height: 50%;
					border: #8a8a8a 4rpx solid;
					border-left: transparent 4rpx solid;
					background-color: transparent;
					border-radius: 0 50% 50% 50%;
					top: 25%;
					left: 25%;
				}
			}
			&.active{
				cover-view,view{
					background-color: #515151;
					&:nth-child(4){
						border: #515151 4rpx solid;
						border-left: transparent 4rpx solid;
						background-color: transparent;
					}
				}
			}
		}
		.chj_icon_right{
			margin-left: 64rpx;
			position: relative;
			width: 48rpx;
			height: 48rpx;
			@extend .flex-center;
			cover-view,view{
				position: absolute;
				border-radius: 4rpx;
				background-color: #8a8a8a;
				&:nth-child(1){
					top: 30%;
					right: 2%;
					width: 25%;
					height: 4rpx;
					transform: rotate(-50deg);
				}
				&:nth-child(2){
					top: 19%;
					right: 2%;
					width: 25%;
					height: 4rpx;
					transform: rotate(50deg);
				}
				&:nth-child(3){
					width: 50%;
					height: 4rpx;
					top: 25%;
					right: 10%;
				}
				&:nth-child(4){
					width: 50%;
					height: 50%;
					border: #8a8a8a 4rpx solid;
					border-right: transparent 4rpx solid;
					background-color: transparent;
					border-radius: 50% 0 50% 50%;
					top: 25%;
					right: 25%;
				}
			}
			&.active{
				cover-view,view{
					background-color: #515151;
					&:nth-child(4){
						border: #515151 4rpx solid;
						border-right: transparent 4rpx solid;
						background-color: transparent;
					}
				}
			}
		}
		.chj_icon_reset{
			width: 48rpx;
			height: 48rpx;
			position: relative;
			@extend .flex-center;
			cover-view,view{
				width: 50%;
				height: 50%;
				position: absolute;
				border-radius: 50%;
				overflow: visible;
				&:nth-child(1){
					border: #515151 4rpx solid;
					border-bottom: transparent 4rpx solid;
					border-right: transparent 4rpx solid;
					transform: rotate(34deg) translate(-5%,-5%);
					&::before{
						content: '';
						background-color: #515151;
						border-radius: 4rpx;
						position: absolute;
						top: 12%;
						right: 1%;
						width: 50%;
						height: 4rpx;
						transform: rotate(-34deg);
						overflow: visible !important;
					}
					&::after{
						content: '';
						background-color: #515151;
						border-radius: 4rpx;
						position: absolute;
						top: -19%;
						right: -1%;
						width: 50%;
						height: 4rpx;
						transform: rotate(54deg);
						overflow: visible !important;
					}
				}
				&:nth-child(2){
					border: #515151 4rpx solid;
					border-top: transparent 4rpx solid;
					border-left: transparent 4rpx solid;
					transform: rotate(34deg) translate(5%,5%);
					&::before{
						content: '';
						background-color: #515151;
						border-radius: 4rpx;
						position: absolute;
						bottom: 12%;
						left: 1%;
						width: 50%;
						height: 4rpx;
						transform: rotate(-34deg);
						overflow: visible !important;
					}
					&::after{
						content: '';
						background-color: #515151;
						border-radius: 4rpx;
						position: absolute;
						bottom: -19%;
						left: -1%;
						width: 50%;
						height: 4rpx;
						transform: rotate(54deg);
						overflow: visible !important;
					}
				}
			}
		}
	}
</style>
